/**********************************
*     yummy      empty
* aib -----> ar <----- fifo (noc)
*     ----->    ----->
*                 ren
**********************************/
module arbiter(
    input clk,
    input rst,
    // mode==1 -> 数据通过mux; mode==0 -> 数据进入config模块
    input mode, 
    input empty0,
    input yummy0,
    output f_ren0,
    input empty1,
    input yummy1,
    output f_ren1,
    input empty2,
    input yummy2,
    output f_ren2,
    output sel,
    output validout
);
    // calculate space used in downstream subnet router
    reg [2:0] su1,su0,su2; 
    always @(posedge clk) begin
        if(rst) begin
            su1<=0;
        end else if(f_ren1 && yummy1) begin
            su1<=su1;
        end else if(f_ren1) begin
            su1<=su1+1;
        end else if(yummy1) begin
            su1<=su1-1;
        end else begin
            su1<=su1;
        end
    end
    always @(posedge clk) begin
        if(rst) begin
            su0<=0;
        end else if(f_ren0 && yummy0) begin
            su0<=su0;
        end else if(f_ren0) begin
            su0<=su0+1;
        end else if(yummy0) begin
            su0<=su0?su0-1:0;
        end else begin
            su0<=su0;
        end
    end
    //add
    always @(posedge clk) begin
        if(rst) begin
            su2<=0;
        end else if(f_ren2 && yummy2) begin
            su2<=su2;
        end else if(f_ren2) begin
            su2<=su2+1;
        end else if(yummy2) begin
            su2<=su2?su2-1:0;
        end else begin
            su2<=su2;
        end
    end
    wire f1=su1==4;
    wire f0=su0==4;
    wire f2=su2==4;

    // subnet 1 has priority
    // 读fifo条件:
    //      1. fifo 非空
    //      2. 下游有空间
    //      3. 当前mode为1
    assign f_ren1 = mode && !empty1 && !f1;
    assign f_ren0 = mode && !f_ren1 && !empty0 && !f0;
    assign f_ren2 = mode && !f_ren1 && !f_ren0 && !empty2 && !f2 ;
    assign sel = ~empty1 && ~f1;
    // assign validout = f_ren1 || f_ren0;
    assign validout = f_ren1 || f_ren0 ||f_ren2;
endmodule
